package finalfinancialanalyst.business;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class IO {
   
    private static final String FOLDER_LOCATION = System.getProperty("user.home") + File.separator + ".final";
    private static final String ACCOUNT_LIST_FILE = "accounts.dat";
    private static final String BUDGET_LIST_FILE = "budgets.dat";
    private static final String CURRENCY_LIST_FILE = "currencies.dat";
    private static final String CATEGORY_LIST_FILE = "categories.dat";
    
    public static File getAccountsFile() {
        return new File(FOLDER_LOCATION + File.separator + ACCOUNT_LIST_FILE);        
    }
    
    public static File getBudgetsFile() {
        return new File(FOLDER_LOCATION + File.separator + BUDGET_LIST_FILE);        
    }
    
    public static File getCurrenciesFile() {
        return new File(FOLDER_LOCATION + File.separator + CURRENCY_LIST_FILE);        
    }
    
    public static File getCategoriesFile() {
        return new File(FOLDER_LOCATION + File.separator + CATEGORY_LIST_FILE);        
    }    
    
    public static boolean writeToFile(Object o, File file) {
         try {
            file.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(o);
            out.close();
            return true;
            }
        catch(IOException ex) {
            ex.printStackTrace();
            return false;
           
        }
        
    }
    
    public static Object loadFromFile(File file) {
        try{
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            Object obj = in.readObject();
            in.close();
            return obj;
        }
        catch(Exception ex)
        {
            return null;
        }        
    }
    
    public static void writeFiles() {
        IO.writeToFile(AccountList.getInstance(), IO.getAccountsFile());
        IO.writeToFile(BudgetList.getInstance(), IO.getBudgetsFile());
        IO.writeToFile(CurrencyList.getInstance(), IO.getCurrenciesFile());
        IO.writeToFile(Categories.getInstance(), IO.getCategoriesFile());
    }

}